<template>
  <base-breadcrumb :title="$route.meta.title">
    <!--  商务成本计划管理月度 -->
    <a-form-model ref="ruleForm" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <a-spin :spinning="loading">
        <fullScreen />
        <!-- 表格 -->
        <a-card :bordered="false">
          <title-name title="基本信息"></title-name>
          <custom-form :formList="formList" :form="form" :is-emit="false" :editModel="editModel == 0 ? '' : ''"> </custom-form>
          <div v-show="form.tips" style="padding: 10px 10px 0 20px; color: #f59a23; border: 1px solid #f5f5f5; margin: 0 40px 10px 40px">
            <p>{{ form.tips }}</p>
          </div>
          <a-upload
            v-if="editModel * 1 === 2"
            class="mb12"
            :show-upload-list="false"
            :custom-request="importFunc"
            accept=".csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          >
            <a-button type="primary">导入</a-button>
          </a-upload>
          <excel v-if="editModel * 1 === 2" ref="exportAll" file-name="导出商务套表模版" is-click-generate="false" class="mb12">
            <a-button :loading="loadingBtn.EXPORT" slot="excelBtn" @click="exportAll"> 导出商务套表模版 </a-button>
          </excel>
          <a-button v-if="editModel*1===1 && dataList && dataList.length" type="primary" @click="setSecondaryAccount"> 展示二级科目 </a-button>
          <p style="text-align: right">单位：元</p>
          <custom-form :formList="formListTwo" :form="form" :is-emit="false" :editModel="editModel == 0 ? '' : ''">
            <template v-slot:table>
              <a-table v-if="dataList && dataList.length" ref="formTable" :loading="loading" bordered :scroll="{x:true}" :columns="columns" :data-source="dataList" :pagination="false" rowKey="id" :defaultExpandAllRows="true" :expandedRowKeys="expandedRowKeys"  @expandedRowsChange="expandedRowsChange">
                <template
                  v-for="col in ['name', 'code', 'actualAmount', 'targetAmount', 'currentTargetAmount', 'cumulativeActualAmount', 'startTime', 'endTime', 'completeStatus', 'description']"
                  :slot="col"
                  slot-scope="text, record, index"
                >
                  <div :key="col" class="form-item">
                    <template>
                      <!-- code 以T结尾，临时节点可以或者不为临时节点层级为2 -->
                      <a-select
                        v-if="col === 'completeStatus' && record.newType && (record.startTime && record.level * 1 !== 1)"
                        placeholder="请选择"
                        :disabled="editModel * 1 === 1"
                        v-model="record[col]"
                      >
                        <a-select-option v-for="(i, index) in completeStatusList" :key="index" :value="i.value">{{ i.label }}</a-select-option>
                      </a-select>
                      <BaseInput v-else-if="col === 'description' && editModel * 1 === 2" v-model="record[col]" style="width: 300px;"></BaseInput>
                      <!-- 返回值不展示 -->
                      <span v-else-if="col === 'completeStatus'"></span>
                      <Ellipsis v-else :length="80" tooltip>{{ record[col] }}</Ellipsis>
                    </template>
                  </div>
                </template>
              </a-table>
            </template>
          </custom-form>
        </a-card>
      </a-spin>
    </a-form-model>
     
    <!-- 页脚操作栏 -->
    <div class="btn_box page-btn-right-top">
      <div v-if="editModel * 1 === 2">
        <a-button class="button_right" v-if="submitStatus * 1 != 1" type="primary" :loading="loadingBtn.DRAFT" @click="handleSubmit(0)">保存草稿</a-button>
        <a-button class="button_right" type="primary" :loading="loadingBtn.SUBMITTED" @click="handleSubmit(1)">提交</a-button>
      </div>
      <a-button @click="handleActiveClose">返回</a-button>
    </div>
    <ErrorTable :visible.sync="visible" :errorData="errorData"></ErrorTable>
  </base-breadcrumb>
</template>

<script>
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import BSelect from '@/components/BComponents/BSelect'
import ErrorTable from './ErrorTable'
import { Ellipsis } from '@/components'
import fullScreen from "../../../../headquartersDashboard/components/fullScreen/fullScreen"
import { placeholder } from '../../../../headquartersDashboard/components/placeholderWay.js'
import { getComBusinessCostMonthlyById, updateByPrimaryKeySelective, importMonthlyExcel, exportMonthlyTemplate,checkExportDetailsChange} from '@/api/businessAffairs/monthlyBusiness'
export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    BSelect,
    ErrorTable,
    Ellipsis,
    fullScreen
  },
  data() {
    this.columns = [
      { title: '序号', width: 160, dataIndex: 'number', align: 'center' },
      {
        title: '项目名称',
        dataIndex: 'name',
        ellipsis: true,
        width: 200
      },
      {
        title: '成本科目编码',
        dataIndex: 'code',
        ellipsis: true,
        width: 120,
      },
      {
        title: '标准成本',
        dataIndex: 'actualAmount',
        ellipsis: true,
        width: 120,
        customRender: (text, row, index) => {
          let zyzbArr = ['JC04','SL04','AZ04','ZS04','TJ04'];
          let codeArr = [],
            azCodeArr = ['AZ04010', 'AZ04011', 'AZ04012', 'AZ04014', 'AZ04018', 'AZ04019', 'AZ04020', 'AZ04021', 'AZ04022'], //安装
            jcCodeArr = ['JC04006', 'JC04007', 'JC04008', 'JC04010', 'JC04011', 'JC04012', 'JC04013', 'JC04014', 'JC04015'], //基础
            zsCodeArr = ['ZS04008', 'ZS04011', 'ZS04012', 'ZS04014', 'ZS04017', 'ZS04018', 'ZS04019', 'ZS04020', 'ZS04021'], //装饰
            fjCodeArr = ['TJ04019', 'TJ04020', 'TJ04021', 'TJ04023', 'TJ04025', 'TJ04026', 'TJ04027', 'TJ04028', 'TJ04029'], //房建
            slCodeArr = ['SL04006', 'SL04007', 'SL04008', 'SL04010', 'SL04011', 'SL04012', 'SL04013', 'SL04014', 'SL04015'] //水利
          codeArr = [...azCodeArr, ...jcCodeArr, ...zsCodeArr, ...fjCodeArr, ...slCodeArr]
          const obj = {
            children: null,
            attrs: {}
          }
          if (codeArr.includes(row.code) && text) {
            obj.children = `${text}%`
          } else {
            obj.children = text ? Number(text).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,') : "";
          }
          if (zyzbArr.includes(row.code)) {
            obj.attrs.colSpan = 6
          }

          return obj
        }
      },
      {
        title: '目标成本',
        dataIndex: 'targetAmount',
        ellipsis: true,
        width: 120,
        customRender: (value, row, index) => { 
          let zyzbArr = ['JC04','SL04','AZ04','ZS04','TJ04'];
          const obj = {
            children: value ? Number(value).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,') : "",
            attrs: {}
          }
          if (zyzbArr.includes(row.code)) {
           obj.attrs.colSpan = 0;
          }
          
          return obj
        }

      },
      {
        title: '当期累计目标成本',
        dataIndex: 'currentTargetAmount',
        ellipsis: true,
        width: 150,
        customRender: (value, row, index) => { 
          let zyzbArr = ['JC04','SL04','AZ04','ZS04','TJ04'];
          const obj = {
            children:  value ? Number(value).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,') : "",
            attrs: {}
          }
          if (zyzbArr.includes(row.code)) {
           obj.attrs.colSpan = 0;
          }
          
          return obj
        }
      },
      {
        title: '累计实际成本',
        dataIndex: 'cumulativeActualAmount',
        ellipsis: true,
        width: 120,
        customRender: (value, row, index) => { 
          let zyzbArr = ['JC04','SL04','AZ04','ZS04','TJ04'];
          const obj = {
            children:  value ? Number(value).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,') : "",
            attrs: {}
          }
          if (zyzbArr.includes(row.code)) {
           obj.attrs.colSpan = 0;
          }
          
          return obj
        }
      },
      {
        title: '节点开始时间',
        dataIndex: 'startTime',
        ellipsis: true,
        width: 120,
        customRender: (value, row, index) => { 
          let newVal = null;
          if(value){
            newVal = value.slice(0,7).replace("-","年") + '月';
          }
          let zyzbArr = ['JC04','SL04','AZ04','ZS04','TJ04'];
          const obj = {
            children: newVal,
            attrs: {}
          }
          if (zyzbArr.includes(row.code)) {
           obj.attrs.colSpan = 0;
          }
          
          return obj
        }
      },
      {
        title: '节点考核时间',
        dataIndex: 'endTime',
        ellipsis: true,
        width: 120,
        customRender: (value, row, index) => { 
          let zyzbArr = ['JC04','SL04','AZ04','ZS04','TJ04'];
          let newVal = null;
          if(value){
            newVal = value.slice(0,7).replace("-","年") + '月';
          }
          const obj = {
            children: newVal,
            attrs: {}
          }
          if (zyzbArr.includes(row.code)) {
           obj.attrs.colSpan = 0;
          }
          
          return obj
        }
      },
      {
        title: '节点完成情况',
        dataIndex: 'completeStatus',
        ellipsis: true,
        width: 120,
        scopedSlots: { customRender: 'completeStatus' },
        // customRender: (value, row, index) => { 
        //   let zyzbArr = ['JC04','SL04','AZ04','ZS04','TJ04'];
        //   const obj = {
        //     children: value,
        //     attrs: {}
        //   }
        //   if (zyzbArr.includes(row.code)) {
        //    obj.attrs.colSpan = 0;
        //   }
          
        //   return obj
        // }
      },
      { title: '备注', dataIndex: 'description', align: 'left', scopedSlots: { customRender: 'description' }, with: 300,}
    ]
    return {
      loading: false, // 加载控件
      visible: false,
      editModel: 0,
      form: {tips:null}, // 表单
      id: '',
      submitStatus: '',
      errorData: [],
      loadingBtn: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false,
        REJECTED: false,
        FILE: false,
        EXPORT: false
      },
      rules: {
        undertakeId: [{ required: true, message: '请选择承接名义' }]
      }, // 校验规则
      dataList: [],
      completeStatusList: [
        { label: '未完成', value: 0 },
        { label: '已完成', value: 1 }
      ],
      expandedRowKeys:[]
    }
  },
  created() {},
  async mounted() {
    if (this.id) {
      this.getDetailData()
    }
  },
  computed: {
    formList() {
      return [
        {
          keyName: 'projectName',
          type: 'a-input',
          disabled: true,
          label: '项目名称'
        },
        {
          keyName: 'monthStr',
          type: 'a-input',
          disabled: true,
          label: '填报期数'
        },
        {
          keyName: 'typeStr',
          type: 'a-input',
          disabled: true,
          label: '业态'
        },
        // {
        //   keyName: 'submitStatusStr',
        //   type: 'a-input',
        //   disabled: true,
        //   hidden: this.editModel * 1 === 2,
        //   label: '项目类型'
        // },
        {
          keyName: 'currentTargetAmount',
          type: 'BaseInputNumber',
          disabled: true,
          label: '当期累计目标成本(元)',
          attrs: {
              formatter: this.limitNumber,
              parser: this.limitNumber
            },
        },
        {
          keyName: 'cumulativeActualAmount',
          type: 'a-input',
          disabled: true,
          label: '当期累计实际成本(元)',
          attrs: {
              formatter: this.limitNumber,
              parser: this.limitNumber
            },
        },
        {
          keyName: 'actualTargetRate',
          type: 'a-input',
          disabled: true,
          label: '累计实际成本/当期累计目标成本',
          attrs: {
              formatter: this.limitNumber,
              parser: this.limitNumber
            },
        }
      ]
    },
    formListTwo() {
      return [
        {
          slot: true,
          customItemSlot: true,
          keyName: 'table',
          span: 24
        }
      ]
    }
  },
  methods: {
    limitNumber(value) {
      if (typeof value === 'string' || typeof value === 'number') {
        return !isNaN(Number(value)) ? Number(value).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,') : ''; 
      } else {
        return ''
      }
    },
     //展开二级科目
     setSecondaryAccount() {
      this.expandedRowKeys = [];
      this.setSecondary(this.dataList)
      console.log(   this.expandedRowKeys)
    },
    setSecondary(data) {
      if (data && data.length) {
        data.forEach((item) => {
          if (item.isShow) {
            this.expandedRowKeys.push(item.id)
          }
          if (item.children && item.children.length) {
            this.setSecondary(item.children)
          } else {
            item.children = null
          }
        })
      }
    },
    expandedRowsChange (expandedRows) {
      this.expandedRowKeys = expandedRows
    },
    getDetailData() {
      // 不为添加时请求详情
      this.loading = true
      getComBusinessCostMonthlyById({ id: this.id })
        .then((res) => {
          if (res.code == '0') {
            this.loading = false
            this.form = { ...this.form, ...res.data }
            this.dataList = this.filterArr(this.IterationDelateMenuChildren(res.data.detailsDTOList))
            // this.dataList =placeholder(this.dataList)
          }
        })
        .catch(() => {
          this.loading = false
        })
    },
    //删除children为空的数据
    IterationDelateMenuChildren(arr) {
      if (arr.length) {
        for (let i in arr) {
          if (arr[i].children.length) {
            this.IterationDelateMenuChildren(arr[i].children)
          } else {
            delete arr[i].children
          }
        }
      }
      return arr
    },
    //过滤，只有直接费和间接费可以编辑
    filterArr(list) {
      let codeArr = ['TJ01', 'TJ02', 'JC01', 'JC02', 'ZS01', 'ZS02', 'AZ01', 'AZ02', 'FJ01', 'FJ02', 'SL01', 'SL02']
      list &&
        list.forEach((item) => {
          if (codeArr.includes(item.code)) {
            this.setType([item])
          }
        })
      return list
    },
    //递归设置属性,
    setType(list) {
      list &&
        list.forEach((item) => {
          item.newType = true //是否是直接费还是间接费,不是一级节点并且有时间才显示
          if (item.startTime && item.level * 1 !== 1) {
            if (!item.completeStatus) {
              //设置默认值
              item.completeStatus = 0
            }
          }
          this.setType(item.children)
        })
      return list
    },

    //导入
    async importFunc(data) {
      this.loading = true
      let fb = new FormData()
      fb.append('file ', data.file)
      fb.append('id ', this.id)
      this.errorData = []
      importMonthlyExcel(fb)
        .then((res) => {
          let suMsgData = res.data || []
          if (res.code == '200') {
              this.form = { ...this.form, ...suMsgData}
              this.dataList = this.filterArr(this.IterationDelateMenuChildren(suMsgData.detailsDTOList))
              // this.visible = true
              // suMsg.forEach((item, index) => {
              //   this.errorData.push({
              //     content: item,
              //     number: index + 1
              //   })
              // })
          }
          this.loading = false
          //this.getDetailData()
        })
        .catch((err) => {
          if (err.code == '501') {
            this.visible = true
          }
          this.loading = false
          let msg = (err.msg && err.msg?.split('\n')) || []
          if (msg.length) {
            msg.forEach((item, index) => {
              this.errorData.push({
                content: item,
                number: index + 1
              })
            })
          }
          if (this.errorData) {
            this.errorData.pop()
          }
        })
    },
    //导出
    exportAll() {
      this.loadingBtn.EXPORT = true;
      //导出提示
      checkExportDetailsChange({id: this.id}).then((res)=>{
         if(res.code == '0'){
          this.loadingBtn.EXPORT = false;
           if(res.data){
         this.$confirm({
            title: '提示?',
            content: '本项目商务计划发生调整，将导出的时候其中三算对比分析表和月度成本分解表将导出为调整后的数据，请知悉。',
            onOk: () => {
              this.exportMonthlyTemplateFn()
            }
          })            
           }else{
             this.exportMonthlyTemplateFn();
           }
         }
      }).catch((err) => {
        this.loadingBtn.EXPORT = false;
      })
    },
    exportMonthlyTemplateFn(){
       this.loadingBtn.EXPORT = true;
      exportMonthlyTemplate({ id: this.id }).then((res) => {
        this.handleDownload(res)
      })
    },
    handleDownload(res) {
      this.loadingBtn.EXPORT = false
      const blob = new Blob([res.data])
      const filename = decodeURIComponent(res.headers['content-disposition']?.split('filename=')[1])
      const downloadElement = document.createElement('a')
      const href = window.URL.createObjectURL(blob) // 创建下载的链接
      downloadElement.href = href
      downloadElement.download = filename // 获取文件名
      document.body.appendChild(downloadElement)
      downloadElement.click() //点击下载
      document.body.removeChild(downloadElement) //下载完成移除元素
      window.URL.revokeObjectURL(href) //释放blob对象
    },
    /**
     * 提交表单
     */
    handleSubmit(status) {
      let params = { ...this.form }
      params.submitStatus = status
      params.detailsDTOList = this.dataList
      if (status === 1) {
        this.$confirm({
          title: '确定是否提交?',
          content: '',
          onOk: () => {
            this.loadingBtn.SUBMITTED = true
            this.submit(params, status)
          }
        })
      } else {
        this.loadingBtn.DRAFT = true
        this.submit(params, status)
      }
    },
    submit(params, status) {
      updateByPrimaryKeySelective(params).then((res) => {
        this.loadingBtn.SUBMITTED = false
        this.loadingBtn.DRAFT = false
        if (res.code == '0') {
          this.$message.success(status === 1 ? '提交成功！' : '保存成功')
          status * 1 === 1 && this.$multiTab.close()
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.updateGeneralAuthorization .ant-btn {
  height: 30px;
}
</style>
